package com.mathlearning.auth.service;

import com.mathlearning.auth.common.BusinessException;
import com.mathlearning.auth.dto.message.*;
import com.mathlearning.auth.entity.Conversation;
import com.mathlearning.auth.entity.Message;
import com.mathlearning.auth.entity.User;
import com.mathlearning.auth.repository.ConversationRepository;
import com.mathlearning.auth.repository.MessageRepository;
import com.mathlearning.auth.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class MessageService {

    private static final Logger logger = LoggerFactory.getLogger(MessageService.class);

    @Autowired
    private MessageRepository messageRepository;

    @Autowired
    private ConversationRepository conversationRepository;

    @Autowired
    private UserRepository userRepository;

    /**
     * 获取会话列表
     */
    public ConversationListResponse getConversations(Long currentUserId, Integer page, Integer pageSize) {
        Pageable pageable = PageRequest.of(page - 1, pageSize);
        Page<Conversation> conversationPage = conversationRepository.findUserConversations(currentUserId, pageable);

        List<ConversationResponse> list = conversationPage.getContent().stream()
                .map(conv -> toConversationResponse(conv, currentUserId))
                .collect(Collectors.toList());

        return new ConversationListResponse(conversationPage.getTotalElements(), list);
    }

    /**
     * 获取与某个用户的聊天记录
     */
    public MessageListResponse getMessagesWith(Long currentUserId, Long otherUserId, Integer page, Integer pageSize) {
        // 检查对方用户是否存在
        if (!userRepository.existsById(otherUserId)) {
            throw new BusinessException("用户不存在");
        }

        Pageable pageable = PageRequest.of(page - 1, pageSize);
        Page<Message> messagePage = messageRepository.findMessagesBetweenUsers(currentUserId, otherUserId, pageable);

        List<MessageResponse> list = messagePage.getContent().stream()
                .map(this::toMessageResponse)
                .collect(Collectors.toList());

        return new MessageListResponse(messagePage.getTotalElements(), list);
    }

    /**
     * 发送私信
     */
    @Transactional
    public MessageResponse sendMessage(Long senderId, SendMessageRequest request) {
        Long receiverId = request.getReceiverId();
        String content = request.getContent();

        // 参数验证
        if (senderId.equals(receiverId)) {
            throw new BusinessException("不能给自己发送私信");
        }

        // 检查接收者是否存在
        if (!userRepository.existsById(receiverId)) {
            throw new BusinessException("接收者不存在");
        }

        // 创建消息
        Message message = new Message();
        message.setSenderId(senderId);
        message.setReceiverId(receiverId);
        message.setContent(content);
        message.setIsRead(false);
        message = messageRepository.save(message);

        // 更新或创建会话
        updateOrCreateConversation(senderId, receiverId, content);

        logger.info("私信发送成功 - 发送者ID: {}, 接收者ID: {}", senderId, receiverId);

        return toMessageResponse(message);
    }

    /**
     * 标记消息为已读
     */
    @Transactional
    public MarkReadResponse markMessagesAsRead(Long currentUserId, Long otherUserId) {
        int count = messageRepository.markMessagesAsRead(otherUserId, currentUserId);
        logger.info("标记消息为已读 - 用户ID: {}, 对方ID: {}, 标记数量: {}", currentUserId, otherUserId, count);
        return new MarkReadResponse(count);
    }

    /**
     * 获取未读消息数量
     */
    public UnreadCountResponse getUnreadCount(Long userId) {
        long count = messageRepository.countUnreadMessages(userId);
        return new UnreadCountResponse(count);
    }

    /**
     * 删除会话
     */
    @Transactional
    public void deleteConversation(Long currentUserId, Long otherUserId) {
        // 删除消息记录
        messageRepository.deleteMessagesBetweenUsers(currentUserId, otherUserId);

        // 删除会话记录
        Long userAId = Math.min(currentUserId, otherUserId);
        Long userBId = Math.max(currentUserId, otherUserId);
        conversationRepository.deleteConversationBetweenUsers(userAId, userBId);

        logger.info("会话删除成功 - 用户ID: {}, 对方ID: {}", currentUserId, otherUserId);
    }

    /**
     * 更新或创建会话
     */
    private void updateOrCreateConversation(Long userId1, Long userId2, String lastMessage) {
        Long userAId = Math.min(userId1, userId2);
        Long userBId = Math.max(userId1, userId2);

        Conversation conversation = conversationRepository.findByUserAIdAndUserBId(userAId, userBId)
                .orElse(Conversation.create(userAId, userBId));

        conversation.setLastMessage(lastMessage);
        conversation.setLastMessageTime(java.time.LocalDateTime.now());
        conversationRepository.save(conversation);
    }

    /**
     * 转换为会话响应
     */
    private ConversationResponse toConversationResponse(Conversation conversation, Long currentUserId) {
        Long otherUserId = conversation.getOtherUserId(currentUserId);
        User otherUser = userRepository.findById(otherUserId).orElse(null);

        ConversationResponse.OtherUserInfo otherUserInfo = new ConversationResponse.OtherUserInfo(
                otherUserId,
                otherUser != null ? otherUser.getNickname() : "未知用户",
                otherUser != null ? otherUser.getAvatar() : null
        );

        // 统计未读消息数量
        long unreadCount = messageRepository.countUnreadMessagesBetweenUsers(otherUserId, currentUserId);

        return new ConversationResponse(
                conversation.getId(),
                otherUserInfo,
                conversation.getLastMessage(),
                conversation.getLastMessageTime(),
                unreadCount
        );
    }

    /**
     * 转换为消息响应
     */
    private MessageResponse toMessageResponse(Message message) {
        return new MessageResponse(
                message.getId(),
                message.getSenderId(),
                message.getReceiverId(),
                message.getContent(),
                message.getCreateTime(),
                message.getIsRead()
        );
    }
}








